<route lang="json5" type="page">
  {
    layout: 'default',
    style: {
      navigationBarTitleText: '订单详情',
    },
    anonymous: false
  }
</route>

<script lang="ts" setup>
import { useToast } from 'wot-design-uni'
import ClassCard from '@/components/ClassCard.vue'
import { useUserStore } from '@/stores'
import getAvatar from '@/utils/avatar'
import { OrderApi, getWxOpenId } from '@/apis'
import { CouponPageType } from '@/enum'

const toast = useToast()
const userStore = useUserStore()
const avatarUrl = getAvatar(null, 1)

const submitLoading = ref(false)
const classList = ref([])
const coupons = ref([])

const gotoCoupon = () => {
  uni.navigateTo({
    url: `/pages/shop/coupon/index?type=${CouponPageType.select}`,
  })
}

const priceMap = ref({})
const orderItemList = ref<OrderApi.OrderItemCreateReq[]>([])

const calculatePrice = async () => {
  const query = {
    studentId: userStore.currentStudent.id,
    orderItemList: orderItemList.value,
    couponIdList: coupons.value,
  }
  const res = await OrderApi.calculatePrice(query)
  priceMap.value = res || {}
}

const onlinePay = (orderId: string) => {
  submitLoading.value = true
  const req = {
    openid: '',
    orderId,
  }
  uni.login({
    provider: 'weixin',
    success: async (res) => {
      if (!res.code) {
        uni.showToast({
          icon: 'error',
          title: '获取微信code失败!',
        })
        submitLoading.value = false
        return
      }
      const sessionRes = await getWxOpenId(res.code)
      req.openid = sessionRes.openid
      OrderApi.onlinePay(req).then((orderInfo) => {
        uni.requestPayment({
          provider: 'wxpay',
          ...orderInfo,
          success: () => {
            uni.navigateTo({ url: '/pages/result/success' })
            // toast.success('支付成功!')
          },
          fail: (fail) => {
            console.warn('支付失败: ', fail)
            uni.showToast({
              icon: 'error',
              title: '支付失败!',
            })
          },
        })
      }).finally(() => {
        submitLoading.value = false
      })
    },
    fail: (fail) => {
      console.log('uni.login调用失败: {}', fail)
      submitLoading.value = false
    },
  })
}

const onCreateOrder = async () => {
  try {
    submitLoading.value = true
    const orderId = await OrderApi.createOrder({
      studentId: userStore.currentStudent.id,
      orderItemList: orderItemList.value,
      payType: 'FUIOU',
      couponIdList: coupons.value,
    })
    uni.setStorageSync('refreshCart', 1)
    onlinePay(orderId)
    toast.info('创建成功，发起支付...')
  } finally {
    submitLoading.value = false
  }
}
onShow(() => {
  const couponList = uni.getStorageSync('couponList')
  if (couponList) {
    coupons.value = JSON.parse(couponList)
    calculatePrice()
  }
  uni.removeStorageSync('couponList')
})

onLoad(() => {
  classList.value = JSON.parse(uni.getStorageSync('orderItemList') ?? '[]')
  orderItemList.value = classList.value.map(item => ({
    classId: item.classId,
    lessonIndexes: item.lessonIndexes,
    // actualTotalPrice: totalPrice.value,
    // actualUnitPrice: item.classInfo.unitPrice,
  }))
  calculatePrice()
})

onUnload(() => {
  uni.removeStorageSync('orderItemList')
})
</script>

<template>
  <view v-if="false" class="flex-row-center-center bg-white page">
    <wd-loading color="#33AD7C" />
  </view>
  <template v-else>
    <view class="content px py">
      <view class="card flex gap-[24rpx]">
        <image
          :src="userStore.currentStudent.avatar || avatarUrl" class="h-100rpx w-[100rpx] border-rd-[8rpx]"
          mode="aspectFill"
        />
        <view class="flex-1">
          <view class="font-size-[30rpx] font-600">
            <text class="mr-1">
              {{ userStore.currentStudent.name }}
            </text>
            <wd-icon
              v-if="userStore.currentStudent.gender === 1" name="gender-male" size="15px"
              color="#597fe8"
            />
            <wd-icon v-else name="gender-female" size="15px" color="#FF0088" />
          </view>
          <view class="mt-[12rpx] flex items-center justify-between">
            <view class="font-size-[26rpx]">
              <text class="color-[#666]">
                入学年份：
              </text>
              <text>{{ userStore.currentStudent.admissionYear || '未知' }}</text>
            </view>
          </view>
        </view>
      </view>

      <view v-for="(item, index) in classList" :key="index">
        <view class="mt-[30rpx]">
          <ClassCard :info="item.classInfo">
            <template #bottom>
              <view class="flex items-center justify-between font-size-[26rpx]">
                <text>购课次数：{{ item.lessonIndexes?.length }}</text>
                <view class="flex items-center">
                  <text>购课总价：</text>
                  <text class="font-size-[36rpx] color-[#cb2e21] font-600">
                    ￥{{ item.classInfo.unitPrice * item.lessonIndexes?.length || 0 }}
                  </text>
                </view>
              </view>
            </template>
          </ClassCard>
        </view>
      </view>

      <view class="card mt-[30rpx]">
        <view class="flex items-center justify-between">
          <view>
            <text class="font-size-[30rpx]">
              课程总价
            </text>
            <text class="ml-[20rpx] font-size-[26rpx] color-[#888]">
              共{{ classList.length }}门课程
            </text>
          </view>
          <PriceText :price="`${priceMap.originalTotalPrice || 0}`" color="#111" />
        </view>
        <view class="mt-[20rpx] flex items-center justify-between">
          <text class="font-size-[30rpx]">
            共减
          </text>
          <PriceText :price="`${priceMap.discountTotalPrice || 0}`" unit="-￥" />
        </view>
        <view class="mt-[20rpx] flex items-center justify-between" @click="gotoCoupon">
          <view class="flex items-center">
            <image src="/static/images/coupon.png" class="h-[40rpx] w-[40rpx]" mode="aspectFill" />
            <text class="ml-[4px] font-size-[30rpx]">
              优惠券
            </text>
          </view>
          <view class="flex items-center">
            <PriceText :price="`${priceMap.couponDiscountPrice || 0}`" unit="-￥" />
            <wd-icon name="arrow-right" class="ml-[4px] mt-[2px]" size="14px" color="#888" />
          </view>
        </view>
        <view class="mt-[20rpx] flex items-center justify-between">
          <view class="flex items-center">
            <image src="/static/images/jian.png" class="h-[40rpx] w-[40rpx]" mode="aspectFill" />
            <text class="ml-[4px] font-size-[30rpx]">
              额外优惠
            </text>
          </view>
          <view class="flex items-center">
            <PriceText :price="`${priceMap.otherDiscountPrice || 0}`" unit="-￥" />
            <!-- <wd-icon name="arrow-right" class="ml-[4px] mt-[2px]" size="14px" color="#888"></wd-icon> -->
          </view>
        </view>
        <view class="mt-[20rpx] flex items-center justify-between">
          <text class="font-size-[30rpx] font-600">
            合计
          </text>
          <PriceText :price="`${priceMap.actualTotalPrice || 0}`" color="#111" />
        </view>
      </view>

      <view class="card mt-[30rpx] flex items-center justify-between">
        <view class="flex items-center">
          <image src="/static/images/wechat.png" class="h-[48rpx] w-[48rpx]" mode="aspectFill" />
          <text class="ml-[10rpx] flex-shrink-0 font-size-[30rpx]">
            微信支付
          </text>
        </view>
        <wd-icon name="check-circle-filled" size="22px" color="#5aab80" />
      </view>
    </view>

    <view class="footer">
      <view class="flex items-center justify-end gap-[20rpx] px-[30rpx] py-[12rpx]">
        <view class="text-right">
          <view class="flex items-center">
            <text class="font-size-[24rpx] color-[#4E5969]">
              共{{ classList.length }}门课程，合计
            </text>
            <PriceText :price="`${priceMap.actualTotalPrice || 0}`" />
          </view>
          <view class="font-size-[24rpx] color-[#DD0A0A]">
            共减 ￥{{ priceMap.discountTotalPrice || 0 }}
          </view>
        </view>
        <view class="flex gap-[24rpx]">
          <wd-button type="success" :round="false" :loading="submitLoading" @click="onCreateOrder">
            立即报名
          </wd-button>
        </view>
      </view>
    </view>
  </template>
</template>

<style lang="scss" scoped>
  .content {
    height: calc(100vh - 160rpx) !important;
    overflow: scroll;
  }

  .footer {
    position: fixed;
    left: 0px;
    bottom: 0px;

    height: 160rpx;
    width: 100%;
    background: white;
    box-shadow: 0px -4px 4px 0px #0000000D;

  }
</style>
